export function groupBy(arr, fn) {
  return arr.map(typeof fn === 'function' ? fn : (val) => val[fn]).reduce((acc, val, i) => {
    acc[val] = (acc[val] || []).concat(arr[i])
    return acc
  }, {})
}

export default function arr2tree(arr, id = 'id', children = 'children', parentId = 'parentId', rootVal = 0) {
  const map = groupBy(arr, parentId)
  const rtv = map[rootVal] || []

  rtv.forEach((item) => {
    setChildren(item, id, children)
  })

  return rtv

  function setChildren(item, id, children) {
    const childrenArr = map[item[id]]

    if (childrenArr) {
      childrenArr.forEach((x) => {
        setChildren(x, id, children)
      })
    }
    item[children] = childrenArr
  }
}
